<!-- 业务授权 -->
<template>
    <div>
        <FormProcess step="1" :registerStatus="this.userStatus" v-if="this.userStatus.accountBinding != 2"/>
        <FormTitle title="业务授权"/>
        <el-row class="check_error_box" v-if="this.userStatus.businessAuthorizationStatus == -1">
            <el-col :span="24" class="check_error_con">&nbsp;<i class="iconfont icon-jingshi"></i>&nbsp;审核未通过原因：{{form.description}}</el-col>
        </el-row>
        <div class="form-box" v-if="this.userStatus.businessAuthorizationStatus != 2">
            <el-form :model="form" ref="form" :rules="rules" label-width="130px" class="demo-ruleForm edit-form-box">
                <el-row class="form-conent-box agent-form-conent">
                    <el-col :span="24">
                        <div class="agent-reminder">
                            授权联系人在汇票线平台操作，授权财务经办人在“兴业执剑人系统”充值、提现等操作。
                        </div>
                    </el-col>
                    <el-col :span="24"><div class="change-default agent-change-default"><el-checkbox v-model="form.chooseDefault" v-bind:disabled="this.isDisable" @change="defaultInfo()">选择联系人默认为经办人</el-checkbox></div></el-col>
                    <el-col :span="24" class="agent-form-int">
                        <div>
                            <el-form-item label="经办人姓名：" prop="agent_treasurer_name">
                                <el-input class="approve-int" v-model="form.agent_treasurer_name" placeholder="请输入经办人姓名" :disabled="this.userStatus.businessAuthorizationStatus == 1"></el-input>
                            </el-form-item>
                            <el-form-item label="经办人身份证：" prop="agent_treasurer_cert_no">
                                <el-input class="approve-int" v-model="form.agent_treasurer_cert_no" placeholder="请输入经办人身份证号" :disabled="this.userStatus.businessAuthorizationStatus == 1"></el-input>
                            </el-form-item>
                            <el-form-item label="经办人手机号：" prop="agent_treasurer_phone">
                                <el-input class="approve-int" v-model="form.agent_treasurer_phone" placeholder="请输入经办人手机号" :disabled="this.userStatus.businessAuthorizationStatus == 1"></el-input>
                            </el-form-item>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="change-default agent-check-box">
                            <el-checkbox-group v-model="form.managerAgreement">
                                <el-checkbox name="managerAgreement" label="1" v-model="form.enterprise_proxy_agree" :disabled="this.userStatus.businessAuthorizationStatus == 1">签订</el-checkbox><el-button type="text" @click="readProxyAgree(true)" class="agent-check-btn">《企业授权委托书》</el-button>
                                <el-checkbox name="managerAgreement" label="2" v-model="form.authorization_cert_agree" :disabled="this.userStatus.businessAuthorizationStatus == 1">签订</el-checkbox><el-button type="text" @click="readProxyAgree(false)">《单位授权书》</el-button>
                            </el-checkbox-group>
                        </div>
                    </el-col>
                    <el-col :span="24" class="agent-form-int">
                        <div class="change-default">
                            <el-checkbox v-model="form.agreeServe" :disabled="this.userStatus.businessAuthorizationStatus == 1">我已阅读并同意<el-button type="text" @click="readServeAgree()">《执剑人用户服务协议》</el-button></el-checkbox>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="submit-btn approve-agent-btn">
                            <el-button type="info" size="small" @click="exitApprove()">取消</el-button>
                            <el-button type="primary" size="small" @click="saveAgent()" v-if="userStatus.businessAuthorizationStatus != 1">提交</el-button>
                            <el-button type="primary" size="small" v-if="userStatus.businessAuthorizationStatus == 1" :disabled="this.userStatus.businessAuthorizationStatus == 1">待审核</el-button>
                        </div>
                    </el-col>
                </el-row>
                <FormDialogEnter ref="enter-dailog" :agentInfo="this.form" :enterInfo="this.userInfo" :protocolShowData="protocolShowData"/>
                <FormDialogUnit ref="unit-dailog" :agentInfo="this.form" :enterInfo="this.userInfo" :protocolShowData="protocolShowData"/>
                <FormDialogServer ref="server-dailog"/>
            </el-form>
        </div>
        <div v-if="this.userStatus.businessAuthorizationStatus == 2">
            <div class="form-box">
                <el-row class="approve-success">
                    <el-col :span="24" class="success-title">
                        已授权
                    </el-col>
                    <el-col :span="24" class="success-con">
                        <div><label>经办人姓名：</label><span>{{this.form.agent_treasurer_name}}</span></div>
                        <div><label>经办人身份证号：</label><span>{{this.form.agent_treasurer_cert_no}}</span></div>
                        <div><label>经办人手机号：</label><span>{{this.form.agent_treasurer_phone}}</span></div>
                    </el-col>
                </el-row>
            </div>
            <div class="go_back"><el-button type="text" @click="exitApprove()"><i class="iconfont icon-fanhui"></i> 返回上一页</el-button></div>
        </div>
    </div>
</template>

<script lang="ts">
    import { Vue, Component, Prop } from 'vue-property-decorator';
    import FormProcess from '@component/common/FormProcess.vue';
    import FormTitle from '@component/common/FormTitle.vue';
    import FormImages from '@component/common/FormImages.vue';
    import FormDialogEnter from '@component/common/FormDialogEnter.vue';
    import FormDialogUnit from '@component/common/FormDialogUnit.vue';
    import FormDialogServer from '@component/common/FormDialogServer.vue';
    import { mapState, mapMutations, mapGetters, mapActions } from 'vuex';
    import { Getter, Action } from 'vuex-class';
    import { checkIDHPX } from '@/util/format';
    import moment from 'moment';
    @Component({
        components: {
            FormProcess,
            FormTitle,
            FormImages,
            FormDialogEnter,
            FormDialogUnit,
            FormDialogServer
        },
        computed: {
            ...mapState([
                "userStatus",
                "userInfo",
                "sysTime"
            ])
        },
        methods: {
            ...mapActions([
                "getPolicy",
                "getStatus",
                "getSysTime"
            ])
        }
    })
    export default class ApproveAgent extends Vue {
        protocolShowData: any = {
            customerName: '',
            customerPhone: '',
            customerIdCart: '',
            angntName: '',
            legalName: '',
            year: '',
            moun: '',
            date: ''
        }
        isDisable: Boolean = false;
        form = {
            agent_treasurer_name: '',
            agent_treasurer_cert_no: '',
            agent_treasurer_phone: '',
            chooseDefault: false,
            agreeServe: true,
            managerAgreement: ['1','2'],
            enterprise_proxy_agree: 'Y',
            authorization_cert_agree: 'Y',
            description: ''
        }
        rules = {
            agent_treasurer_name: [
                {required: true, message: '请输入经办人姓名', trigger: 'blur'}
            ],
            agent_treasurer_cert_no: [
                { required: true, message: '请输入经办人身份证号', trigger: 'blur' },
                // {
                //     pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/,
                //     message: '经办人身份证号错误',
                //     trigger: 'blur'
                // }
            ],
            agent_treasurer_phone: [
                { required: true, message: '请输入经办人手机号码', trigger: 'blur' },
                {
                    pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
                    message: '经办人手机号码错误',
                    trigger: 'blur'
                }
            ]
        }
        // 选择默认联系人
        defaultInfo () {
            if(this.form.chooseDefault){
                // 获取联系人信息
                this.$http.get(`customers/customer/${this.userInfo.customer_id}`)
                    .then((response) => {
                        this.form.agent_treasurer_name = response.data.customer_name;
                        this.form.agent_treasurer_cert_no = response.data.id_number;
                        this.form.agent_treasurer_phone = response.data.phone_number;
                    })
            }else {
                this.form.agent_treasurer_name = '';
                this.form.agent_treasurer_cert_no = '';
                this.form.agent_treasurer_phone = '';
            }
        }

        // 执剑人用户协议弹窗
        readServeAgree () {
            this.$refs['server-dailog'].openDialog();
        }
        async getLegalInfo () {
            let res = await this.$http.get(`enterpriseXingyeUser/getLegalInfo?enterpriseId=${this.userInfo.enterprise_id}`)
            if (res.status == 200) {
                this.protocolShowData.legalName = res.data.legalName;
            }
        }
        async getCustomerInfo () {
            let res = await this.$http.get(`customers/customer/${this.userInfo.customer_id}`)
            if (res.status == 200) {
                this.protocolShowData.customerPhone = res.data.phone_number
                this.protocolShowData.customerIdCart = res.data.id_number
            }
        }
        // 企业授权书和单位授权书
        readProxyAgree (way) {
            if(!this.form.agent_treasurer_name){
                this.$alert('请先输入经办人姓名。','提示',{
                    confirmButtonText: '确定',
                    customClass: 'custom-message-box',
                    callback: action => {}
                });
                return;
            }
            if(!this.form.agent_treasurer_cert_no){
                this.$alert('请先输入经办人身份证号。','提示',{
                    confirmButtonText: '确定',
                    customClass: 'custom-message-box',
                    center: true,
                    callback: action => {}
                });
                return;
            }
            if(this.form.agent_treasurer_cert_no != '' && !checkIDHPX(this.form.agent_treasurer_cert_no)){
                this.$alert('请输入正确的经办人身份证号。','提示',{
                    confirmButtonText: '确定',
                    customClass: 'custom-message-box',
                    center: true,
                    callback: action => {}
                });
                return;
            }
            if(!this.form.agent_treasurer_phone){
                this.$alert('请先输入经办人手机号。','提示',{
                    confirmButtonText: '确定',
                    customClass: 'custom-message-box',
                    callback: action => {}
                });
                return;
            }
            this.protocolShowData.customerName = this.userInfo.customer_name;
            this.protocolShowData.angntName = this.form.agent_treasurer_name;
            let promiseLegal = this.getLegalInfo()
            let promseCustomer = this.getCustomerInfo()
            Promise.all([promiseLegal, promseCustomer]).then(() => {
                if(way){
                    this.$refs['enter-dailog'].openDialog();
                }else{
                    this.$refs['unit-dailog'].openDialog();
                }
            })
            // promiseLegal.then(() => {
            //     promseCustomer.then(() => {
            //         if(way){
            //             this.$refs['enter-dailog'].openDialog();
            //         }else{
            //             this.$refs['unit-dailog'].openDialog();
            //         }
            //     })
            // })
        }
        // 点击保存经办人
        saveAgent () {
            if(this.form.managerAgreement.length < 2){
                this.$alert('请先签订《企业授权委托书》和《单位授权书》。','提示',{
                    confirmButtonText: '确定',
                    customClass: 'custom-message-box',
                    center: true,
                    callback: action => {}
                });
                return;
            }
            if(!this.form.agreeServe){
                this.$alert('请先阅读并同意《执剑人用户服务协议》','提示',{
                    confirmButtonText: '确定',
                    customClass: 'custom-message-box',
                    center: true,
                    callback: action => {}
                })
                return;
            }
            if(this.form.agent_treasurer_cert_no != '' && !checkIDHPX(this.form.agent_treasurer_cert_no)){
                this.$alert('请输入正确的经办人身份证号。','提示',{
                    confirmButtonText: '确定',
                    customClass: 'custom-message-box',
                    center: true,
                    callback: action => {}
                });
                return;
            }
            this.$refs.form.validate((valid) => {
                // 发送请求
                let agentForm = this.form;
                if(valid){
                    if(this.userStatus.businessAuthorizationStatus == 0){
                        this.agentPost(agentForm);
                    }else if(this.userStatus.businessAuthorizationStatus == -1){
                        this.agentPut(agentForm);
                    }
                }
            })
        }
        async agentPost (agentForm) {
            let res = await this.$http.post(`paying/xingyeapi/insertAgentTreasurer2/${this.userInfo.enterprise_id}`,agentForm)
            this.getStatus();
            if(res.status == 200){
                this.$confirm('经办人保存成功，等待管理员审核。请进行账户绑定！','提醒',{
                    confirmButtonText: '继续',
                    cancelButtonText: '以后再说',
                    customClass: 'custom-message-box',
                    center: true
                }).then(() => {
                    this.$router.push('/approveAccount');
                }).catch(() => {
                    location.href='/trade.html';
                })
            }
        }
        async agentPut (agentForm) {
            let res = await this.$http.put(`paying/xingyeapi/updateAgentTreasurer/${this.userInfo.enterprise_id}`,agentForm)
            this.getStatus();
            if(res.status == 200){
                this.$confirm('经办人修改成功，等待管理员审核。','提醒',{
                    confirmButtonText: '继续',
                    cancelButtonText: '以后再说',
                    customClass: 'custom-message-box',
                    center: true
                }).then(() => {
                    if(this.userStatus.accountBinding == 0){
                        this.$router.push('/approveAccount');
                    }else {
                        location.href='/trade.html';
                    }
                })
            }
        }
        // 获取经办人信息
        getAgent () {
            if(this.userStatus.businessAuthorizationStatus != 0){
                this.$http.get(`paying/xingyeapi/selectAgentTreasurer/${this.userInfo.enterprise_id}`)
                    .then((response) => {
                        if (response.status < 300){
                            this.form.agent_treasurer_name = response.data.agent_treasurer_name;
                            this.form.agent_treasurer_cert_no = response.data.agent_treasurer_cert_no;
                            this.form.agent_treasurer_phone = response.data.agent_treasurer_phone;
                            this.form.description = response.data.description
                            if(this.form.agent_treasurer_name == this.userInfo.customer_name){
                                this.form.chooseDefault = true;
                                this.isDisable = true;
                            }
                        }
                    })
            }
        }
        // 退出认证
        exitApprove () {
            let backUrl = /back=.+$/.exec(location.hash);
            location.href = backUrl && backUrl.length == 1 ? backUrl[0].split('=')[1] : "/trade.html";
        }
        created () {
            let promise = this.getStatus();
            let self = this;
            promise.then(resolve => {
                this.getAgent();
                this.getPolicy();
            })
        }

        mounted () {
            let promiseTime = this.getSysTime();
            promiseTime.then(() => {
                this.protocolShowData.year = moment(this.sysTime).format('YYYY');
                this.protocolShowData.moun = moment(this.sysTime).format('MM');
                this.protocolShowData.date = moment(this.sysTime).format('DD')
            })
        }
    }
</script>

<style lang="scss" scoped>
    .agent-reminder-sign {
        display: flex;
        justify-content: center;
        height: 32px;
        align-items: center;
        background: $__color-bg-unimportance;
    }
    .agent-reminder {
        @extend .agent-reminder-sign;
        color: $__color-primary;
    }
    .agent-form-int {
        display: flex;
        justify-content: center;
    }
    .change-default {
        text-align: center;
        font-size: $__little-font-size;
        .el-button--text {
            color: $__color-link;
        }
    }
    .agent-check-btn {
        margin-right: 30px;
    }
    .agent-change-default {
        margin-top: 40px;
        margin-bottom: 30px;
    }
    .agent-check-box {
        @extend .agent-reminder-sign;
        margin-top: 35px;
        margin-bottom: 45px;
    }
    .approve-agent-btn {
        margin-left: 370px;
        .el-button:nth-child(1){
            margin-right: 12px;
        }
    }
    .success-con {
        label {
            color: $__color-label;
            display: inline-block;
            width: 45%;
            text-align: right;
        }
        span{
            display: inline-block;
            width: 55%;
            text-align: left;
        }
    }
    .go_back {
        display: flex;
        justify-content: center;
        .el-button--text {
            color: $__color-link;
        }
    }
</style>
<style lang="scss">
    .agent-form-conent {
        width: 924px;
    }
</style>